import router from './router'
import store from './store'
import { getToken } from './utils/auth'

// 导航守卫逻辑
router.beforeEach(async (to, from, next) => {
  const token = getToken();
  const whiteList = ["/login", "/404"];
  if (token) {
    // 有 token
    if (to.path === "/login") {
      // 去首页
      next("/");
    } else {
      // await store.dispatch("user/getUserProfileAction");
      // next();
      // // console.log(store);
      // // console.log(store.getters.userId);
      // // if (!store.getters.userId) {
      // //   // 获取用户资料
      // //   await store.dispatch('user/getUserProfileAction')
      // // }


      // console.log(!store.getters.userId, '===1');
      if (!store.getters.userId) {
        // 获取用户资料
        let { permission_menu_list } = await store.dispatch(
          "user/getUserProfileAction"
        );
        let userAsyncRoute = await store.dispatch(
          "permissions/generatorRoutes",
          permission_menu_list
        );
        // console.log(userAsyncRoute);
        router.addRoutes(userAsyncRoute);
        next(to.path);
      } else {
        next();
      }
    }
  } else {
    // 无 token
    if (whiteList.includes(to.path)) {
      // 放行
      next();
    } else {
      // 拦截
      next("/login");
    }
  }
});

// 全局后置守卫
router.afterEach(() => {});